package xps.and.uudaijia.userclient.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.jude.utils.JUtils;
import com.neovisionaries.ws.client.PayloadGenerator;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketExtension;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.data.baen.RequestParams;


public class RemoteService extends Service {

    WebSocket webSocket;
    private static final String SERVER = "ws://60.205.149.135:8585";
    //  private static final String SERVER = "ws://60.205.149.135:8686";
    private static final int TIMEOUT = 5000;
    private MyConnection conn;
    private String userId;

    @Override
    public void onCreate() {
        super.onCreate();
        if (conn == null)
            conn = new MyConnection();

        new Thread() {
            @Override
            public void run() {
                super.run();
                connectToServer();
            }
        }.start();

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("UU智行");
        builder.setContentText("UU智行正在运行...");
        startForeground(250, builder.build());
        userId = intent.getStringExtra("userId");
    }


    private class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (webSocket != null)
                webSocket.disconnect();
        }
    }

    void connectToServer() {
        try {
            webSocket = new WebSocketFactory()
                    .setConnectionTimeout(TIMEOUT)
                    .createSocket(SERVER)
                    .addListener(new MySocketAdapter())
                    .setPingPayloadGenerator(new PayloadGenerator() {
                        @Override
                        public byte[] generate() {
                            return RequestParams.getNewInstance().setType("pong").getJson().toString().getBytes();
                        }
                    })
                    .setPingInterval(1000 * 10)
                    .addExtension(WebSocketExtension.PERMESSAGE_DEFLATE).connect();
            SharedPreferences sp = JUtils.getSharedPreference();
            if (!TextUtils.isEmpty(sp.getString("User_ID", ""))) {
                userId = sp.getString("User_ID", "");
            }
            webSocket.sendText(RequestParams.getNewInstance().setType("auth").setUid(userId).getJson().toString());
        } catch (WebSocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webSocket != null)
            webSocket.disconnect();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MySocketAdapter extends WebSocketAdapter {
        public void onTextMessage(WebSocket websocket, String message) {
            Log.e("Mainactivity", "onTextMessage" + message);
            Intent intent = new Intent();
            intent.putExtra("count", message);
            intent.setAction("xps.and.uudaijia.userclient.service.RemoteService");
            sendBroadcast(intent);
        }

        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
            super.onConnected(websocket, headers);
            Log.e("Mainactivity", "onConnected");
        }

        @Override
        public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
            super.onFrameSent(websocket, frame);
            Log.e("Mainactivity", "onFrameSent" + frame);
        }
    }

}
